package com.mashibing.dp.Iterator.v7;

/**
 * 相比数组，这个容器不用考虑边界问题，可以动态扩展
 */
class LinkedList_<E> implements Collection_<E> {
    Node head = null;
    Node tail = null;
    //目前容器中有多少个元素
    private int size = 0;

    @Override
    public void add(E o) {
        Node n = new Node(o);
        n.next = null;

        if(head == null) {
            head = n;
            tail = n;
        }

        tail.next = n;
        tail = n;
        size++;
    }

    private class Node {
        private E o;
        Node next;

        public Node(E o) {
            this.o = o;
        }
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public Iterator_ iterator() {
        return new LinkedListIterator();
    }

    private class LinkedListIterator<E> implements Iterator_<E> {

        private int currentIndex = 0;

        @Override
        public boolean hasNext() {
            if(currentIndex >= size) return false;
            return true;
        }

        @Override
        public E next() {
            E o = null;
            if(hasNext()) {
                o = (E) head.o;
                head = head.next;
                currentIndex++;
            }
            return o;
        }
    }
}
